package com.jhj.common.view;

import org.apache.velocity.context.Context;
import org.springframework.web.servlet.view.velocity.VelocityLayoutView;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Velocity view
 * 
 * @author GaoXiang Date: 2014-7-17
 */
public class JhjVelocityLayoutView extends VelocityLayoutView {
    
    /**
     * 存放公共url的map
     */
    private Map<String, String> velocityUrl;
    
    /**
     * 页面工具类
     */
    private Map<String, Object> velocityTools;
    
    /**
     * 渲染页面公共内容
     * 
     * @param context
     * @param response
     * @throws Exception
     */
    protected void doRender(Context context, HttpServletResponse response) throws Exception {
        // 将公共url merge到页面
        mergeUrl(context, velocityUrl);
        // 渲染工具类到页面
        merge(context, velocityTools);
        // 渲染页面内容
        super.doRender(context, response);
    }
    
    /**
     * 将公共url注入到context
     * 
     * @param context
     * @param map
     */
    private void mergeUrl(Context context, Map<String, String> map) {
        if (map != null) {
            for (Map.Entry<String, String> stringUrlEntry : map.entrySet()) {
                String key = stringUrlEntry.getKey();
                String url = stringUrlEntry.getValue();
                context.put(key, url);
            }
        }
    }
    
    private void merge(Context context, Map<String, Object> map) {
        if (map != null) {
            for (Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {
                context.put(stringObjectEntry.getKey(), stringObjectEntry.getValue());
            }
        }
    }
    
    public void setVelocityUrl(Map<String, String> velocityUrl) {
        this.velocityUrl = velocityUrl;
    }
    
    public void setVelocityTools(Map<String, Object> velocityTools) {
        this.velocityTools = velocityTools;
    }
}
